/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.terramagnet.mvcframework;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.Serializable;

/**
 * 接口返回值基础类.
 *
 * @author lip
 */
public class PrimaryResponse<T> implements Serializable {

    /**
     * 操作成功返回{@code 0}.
     *
     */
    private int code;
    /**
     * 用户客户端提示的信息.
     */
    private String message;
    /**
     * 接口返回的对象.
     */
    private T data;

    public PrimaryResponse() {
    }

    public PrimaryResponse(T data) {
        this.data = data;
    }

    /**
     * 操作成功返回{@code 0}.
     *
     * @return the code
     */
    public int getCode() {
        return code;
    }

    /**
     * 操作成功返回{@code 0}.
     *
     * @param code the code to set
     */
    public void setCode(int code) {
        this.code = code;
    }

    /**
     * 用户客户端提示的信息.
     *
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * 用户客户端提示的信息.
     *
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * 接口返回的对象.
     *
     * @return the data
     */
    public T getData() {
        return data;
    }

    /**
     * 接口返回的对象.
     *
     * @param data the data to set
     */
    public void setData(T data) {
        this.data = data;
    }

    /**
     * 接口调用是否成功.
     */
    @JsonIgnore
    public boolean isSuccessful() {
        return this.code == 0;
    }

    /**
     * 接口调用是否失败.
     */
    @JsonIgnore
    public boolean isFailed() {
        return this.code != 0;
    }

    @Override
    public String toString() {
        try {
            return jsonUtil.writeValueAsString(this);
        } catch (IOException ex) {
            return "{" + "code=" + code + ", message=" + message + ", data=" + data + '}';
        }
    }
    private static final ObjectMapper jsonUtil = new ObjectMapper();
}
